package com.module.retrofit.utils;

import com.module.retrofit.ApplicationHelper;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import androidx.annotation.Nullable;

/**
 * @Author: dengqi
 * @CreateDate: 2020/10/19 10:37
 * @Description:
 */
public class HeaderUtils {

    public static final String CACHE_HEADER = "cache_header";

    /**
     * 设置单个header
     * @param key
     * @param value
     */
    public static void setHeader(@Nullable String key, @Nullable String value) {
        Map<String, String> headers = getHeaders();
        if(headers==null){
            headers = new LinkedHashMap<>();
        }
        headers.put(key, value);
        saveHeaders(headers);
    }

    /**
     * 设置多个header
     * @param maps
     */
    public static void setHeaders(@Nullable Map<String, String> maps) {
        Map<String, String> headers = getHeaders();
        if(headers==null){
            headers = new LinkedHashMap<>();
        }
        headers.putAll(maps);
        saveHeaders(headers);
    }

    /**
     * 保存headr
     */
    public static void saveHeaders(Map<String, String> headers){
        ACache mCache = ACache.get(ApplicationHelper.getContext());
        mCache.put(CACHE_HEADER,(Serializable) headers);
    }

    public static Map<String, String> getHeaders(){
        ACache mCache = ACache.get(ApplicationHelper.getContext());
        return (Map<String, String>) mCache.getAsObject(CACHE_HEADER);

    }

    /**
     * 删除全部header
     */
    public static void clearHeaders() {
        ACache mCache = ACache.get(ApplicationHelper.getContext());
        mCache.remove(CACHE_HEADER);
    }

    /**
     * 删除单个header
     * @param key
     */
    public static void clearHeaders(@Nullable String key) {
        Map<String, String> headers = getHeaders();
        if(headers!=null){
            headers.remove(key);
            saveHeaders(headers);
        }
    }
}
